package com.jzdjt.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.jzdjt.entity.UserEntity;
import com.jzdjt.tool.ChangeToPY;
import com.jzdjt.tool.DBUtil;

public class UpdateStudentServlet extends HttpServlet {

	public UpdateStudentServlet() {
		super();
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");

		// 根据标示名获取JSP文件中表单所包含的参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String mobile = request.getParameter("mobile");
		String region = request.getParameter("region");
		String school = request.getParameter("school");
		String classstr = request.getParameter("classstr");
		String bothday = request.getParameter("bothday");
		String grade = request.getParameter("grade");
		String subject = request.getParameter("subject");
		String gendar = request.getParameter("gendar");
		int result = updateSql(username, password, mobile, region, bothday, school, classstr, grade, subject, gendar);

		PrintWriter out = response.getWriter();// 回应请求

		out.write(result + "");
		out.flush();
		out.close();
		System.out.println(result);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// doGet(request, response);
		// 设置客户端的解码方式为utf-8
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");

		// 根据标示名获取JSP文件中表单所包含的参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String mobile = request.getParameter("mobile");
		String region = request.getParameter("region");
		String school = request.getParameter("school");
		String classstr = request.getParameter("classstr");
		String bothday = request.getParameter("bothday");
		String grade = request.getParameter("grade");
		String subject = request.getParameter("subject");
		String gendar = request.getParameter("gendar");
		int result = updateSql(username, password, mobile, region, bothday, school, classstr, grade, subject, gendar);

		PrintWriter out = response.getWriter();// 回应请求

		out.write(result + "");
		out.flush();
		out.close();
		System.out.println(result);
	}

	private int updateSql(String username, String password, String mobile, String region, String bothday, String school,
			String classstr, String grade, String subject, String gendar) {
		int rets = 0;

		try {
			Date d = new Date(); // 获取当前系统的时间
			// 格式化日期
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			String RegisterDateTime = sdf.format(d); // 转为字符串

			String selectsql = "select * from student where phonenumber='" + mobile + "'";
			DBUtil dbUtil = new DBUtil();
			List<UserEntity> getlist = dbUtil.QueryFromStudent(selectsql);
			if (getlist != null && getlist.size() == 0) {
				String[] regions = region.split("\\s+");
				String[] regions_py = new String[3];
				if (regions.length == 3) {
					ChangeToPY cte = new ChangeToPY();

					String region1 = cte.getAllFirstLetter(regions[0]);
					if (region1 != null && region1.length() >= 2) {
						regions_py[0] = region1.substring(0, 2).toUpperCase();
					}
					String region2 = cte.getAllFirstLetter(regions[1]);
					if (region2 != null && region2.length() >= 2) {
						regions_py[1] = region2.substring(0, 2).toUpperCase();
					}
					String region3 = cte.getAllFirstLetter(regions[2]);
					if (region3 != null && region3.length() >= 2) {
						regions_py[2] = region3.substring(0, 2).toUpperCase();
					}
					String gradeid = getGradeId(grade);
					String studId = "";
					// 地区首字母，省市区+年级编码+班级代码+手机号
					studId = regions_py[0] + regions_py[1] + regions_py[2] + gradeid + classstr + mobile;
                    String classnum = "";
					if(classstr.equals("01")){
                    	classnum ="1";
                    }
					else if(classstr.equals("02")){
                    	classnum ="2";
                    }
					
					else if(classstr.equals("03")){
                    	classnum ="3";
                    }

					else if(classstr.equals("04")){
                    	classnum ="4";
                    }

					else if(classstr.equals("05")){
                    	classnum ="5";
                    }
					else if(classstr.equals("06")){
                    	classnum ="6";
                    }

					else if(classstr.equals("07")){
                    	classnum ="7";
                    }
					else if(classstr.equals("08")){
                    	classnum ="8";
                    }

					else if(classstr.equals("09")){
                    	classnum ="9";
                    }
					else {
                    	classnum =classstr;
                    }

					
					String insertSql = "insert into student(studentId,name,gender,province,city,county,school,grade,class,birthDate,subjects,registerDate,phonenumber,password,balance) "
							+ " values('" + studId + "','" + username + "','" + gendar + "','" + regions[0] + "','"
							+ regions[1] + "','" + regions[2] + "','" + school + "'," + "'" + grade + "','" + classnum
							+ "','" + bothday + "','" + subject + "','" + RegisterDateTime + "','" + mobile + "','"
							+ password + "','fdOWBNuU/sg=') ";
					dbUtil.update(insertSql);
					// http://121.40.78.35:8080/yxthttp/sms/sendUTF8
					HttpClient httpClient = new DefaultHttpClient();

					// 设置超时时间
					httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
					httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
					String url = "http://121.40.78.35:8080/yxthttp/sms/sendUTF8";
//					String url = "http://121.40.78.35:8080/yxthttp/sms/remainpoint";
					HttpPost post = new HttpPost(url);
					// 构造消息头
					post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
					post.setHeader("Connection", "Close");
					String content ="【国民教育】"+username+"同学您好，欢迎使用<智慧精准名师课堂>，您的帐号注册成功，登录帐号为注册手机号！";
					String sendstr = "action=send&userid=10124&account=1jxgmjy4&password=sCdiTo&mobile="+mobile+"&content="+content;
					//String sendstr = "action=send&userid=11726&account=jxgmjy&password=X2qnAv&mobile="+mobile+"&content="+content;
//					String sendstr = "action=overage&userid=11726&account=jxgmjy&password=X2qnAv";
					// 构建消息实体
					StringEntity entity = new StringEntity(sendstr, Charset.forName("UTF-8"));
					entity.setContentEncoding("UTF-8");
					// 发送Json格式的数据请求
					entity.setContentType("text/plain");
					post.setEntity(entity);

					try {
						HttpResponse response = httpClient.execute(post);
						HttpEntity entityr = response.getEntity();
						if (entityr != null) {
							// 将返回的数据直接转成String
							String str = EntityUtils.toString(entityr, "UTF-8");
							System.out.println("--------------------------------------");
							// 注意这里不能写成EntityUtils.toString(entity,
							// "UTF-8"),因为EntityUtils只能调用一次，否则会报错：java.io.IOException:
							// Attempted read from closed stream
							System.out.println("Response content: " + str);
							System.out.println("--------------------------------------");

							// 这里用str作为参数获得 Document 对象
							Document document;
							try {
								document = DocumentHelper.parseText(str);
								Element rootElement = document.getRootElement();
								String status = rootElement.element("returnstatus").getText();
								if(status!=null&&status.toLowerCase().equals("success")){
									
								}
								else{
									String msg = rootElement.element("message").getText();
									System.out.println(msg);
								}
 							} catch (DocumentException e) {
								// TODO Auto-generated catch block
 								System.out.println(e.getMessage());
								//e.printStackTrace();
							} 
						}
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						System.out.println(e.getMessage());
						//e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						System.out.println(e.getMessage());
						//e.printStackTrace();
					}
					return 1;
				} else {
					System.out.println("地区格式错误，无法保存用户记录");
					return 0;
				}

			} else {
				System.out.println("用户已存在");
				return 2;
			}

		} catch (SQLException e) {
			System.out.println(e.getMessage());
			//e.printStackTrace();
			return 0;
		}
	}

	private String getGradeId(String gradestr) {
		String gradeid = "01";
		if (gradestr.equals("小学一年级")) {
			gradeid = "01";
		} else if (gradestr.equals("小学二年级")) {
			gradeid = "02";

		} else if (gradestr.equals("小学三年级")) {
			gradeid = "03";

		} else if (gradestr.equals("小学四年级")) {
			gradeid = "04";

		} else if (gradestr.equals("小学五年级")) {
			gradeid = "05";

		} else if (gradestr.equals("小学六年级")) {
			gradeid = "06";

		} else if (gradestr.equals("初中一年级")) {
			gradeid = "07";

		} else if (gradestr.equals("初中二年级")) {
			gradeid = "08";

		} else if (gradestr.equals("初中三年级")) {
			gradeid = "09";

		} else if (gradestr.equals("高中一年级")) {
			gradeid = "10";

		} else if (gradestr.equals("高中二年级")) {
			gradeid = "11";

		} else if (gradestr.equals("高中三年级")) {
			gradeid = "12";

		}
		return gradeid;
	}

}